﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace SPN.WebParts.Subscribe
{
    public partial class SubscribeUserControl : UserControl
    {
        #region Properties
        public string _Settings_WebUrl { get; set; }
        public string _Label_HeaderTitle { get; set; }
        public string _Label_SubscribeRadioButtonText { get; set; }
        public string _Label_UnSubscribeRadioButtonText { get; set; }
        public string _Label_SubmitButton { get; set; }
        public string _Label_EmailText { get; set; }
        public string _Label_SubscribedText { get; set; }
        public string _Label_AlreadySubscribedText { get; set; }
        public string _Label_UnSubscribedText { get; set; }
        public string _Label_EmailNotValid { get; set; }
        #endregion

        #region PageEvents
        protected void Page_Load(object sender, EventArgs e)
        {
            CssRegistration.Register("/_layouts/SPN/css/main.css");
            if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Display)
            {
                this.Visible = true;
                if (!IsPostBack)
                {
                    lab_Header.Text = _Label_HeaderTitle;
                    lab_Text.Text = _Label_EmailText;
                    lib_Submit.Text = _Label_SubmitButton;
                    rev_eMail.Text = _Label_EmailNotValid;
                    rb_Subscribe.Text = _Label_SubscribeRadioButtonText;
                    rb_UnSubscribe.Text = _Label_UnSubscribeRadioButtonText;
                    if (_Settings_WebUrl != "")
                    {
                        SPWeb _Web = null;
                        try 
                        { 
                            _Web = SPContext.Current.Site.AllWebs[_Settings_WebUrl];
                            string _UrlValue = _Web.ServerRelativeUrl;
                        }
                        catch 
                        {
                            _Web = null;
                        }
                        if (_Web != null)
                        {
                            List<string> _Values = new List<string>();
                            _Values.Add(Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_ConfirmationUrl));
                            _Values.Add(Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_SubscribeEmailFrom));
                            _Values.Add(Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_SubscribeEmailSubject));
                            _Values.Add(Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_SubscribeEmailLinkText));
                            _Values.Add(Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_UnSubscribeEmailFrom));
                            _Values.Add(Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_UnSubscribeEmailSubject));
                            _Values.Add(Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_UnSubscribeEmailLinkText));
                            if (!IsValid(_Values))
                            {
                                this.ControlsVisibility(false);
                                lab_Message.Text = "Newsletter is not configured.";
                            }
                        }
                        else 
                        {
                            this.ControlsVisibility(false);
                            lab_Message.Text = "Entered WebUrl is not valid.";
                        }
                    }
                    else 
                    {
                        this.ControlsVisibility(false);
                        lab_Message.Text = "Web Part is not configured. WebUrl is missing.";
                    }
                }
            }
            else if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Edit)
            {
                this.Visible = false;
            }
        }
        #endregion

        #region ControlsEvents
        protected void lib_Submit_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite _Site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb _Web = _Site.AllWebs[SPContext.Current.Web.ID])
                    {
                        List<string> _Values = new List<string>();
                        //=======================================================================================================================>>
                        string _Value_ConfirmationUrl = Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_ConfirmationUrl);
                        //=======================================================================================================================>>
                        string _Value_SubscribeEmailFrom = Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_SubscribeEmailFrom);
                        string _Value_SubscribeEmailSubject = Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_SubscribeEmailSubject);
                        string _Value_SubscribeEmailContent = Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_SubscribeEmailContent);
                        string _Value_SubscribeEmailLinkText = Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_SubscribeEmailLinkText);
                        string _Value_UnSubscribeEmailFrom = Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_UnSubscribeEmailFrom);
                        string _Value_UnSubscribeEmailSubject = Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_UnSubscribeEmailSubject);
                        string _Value_UnSubscribeEmailContent = Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_UnSubscribeEmailContent);
                        string _Value_UnSubscribeEmailLinkText = Common.Helper.GetWebProperty(_Web, Common.Helper._SPN_UnSubscribeEmailLinkText);
                        //=======================================================================================================================>>
                        if (Common.Helper.IsListValid(_Web, Common.Helper._Const_SubscriberListName) && Common.Helper.IsListValid(_Web, Common.Helper._Const_NewsletterListName))
                        {
                            SPListItemCollection _Subscribers = _Web.Lists[Common.Helper._Const_SubscriberListName].Items;
                            bool _EmailExist = false;
                            for (int i = 0; i < _Subscribers.Count; i++)
                            {
                                SPListItem _Subscriber = _Subscribers[i];
                                if (_Subscriber["Title"].ToString() == tb_eMail.Text)
                                {
                                    _EmailExist = true;
                                }
                            }
                            if (rb_Subscribe.Checked)
                            {
                                if (!_EmailExist)
                                {
                                    SPListItem _ListItem = _Subscribers.Add();
                                    Guid _ActivationCode;
                                    _ActivationCode = Guid.NewGuid();
                                    _ListItem["Title"] = tb_eMail.Text;
                                    _ListItem["Active"] = false;
                                    _ListItem["Activation code"] = _ActivationCode.ToString();
                                    _ListItem["ContentType"] = "eTic Portal - Subscriber";
                                    _Web.AllowUnsafeUpdates = true;
                                    _ListItem.Update();
                                    _Web.AllowUnsafeUpdates = false;

                                    StringDictionary _EmailHeaders = new StringDictionary();
                                    _EmailHeaders.Add("to", tb_eMail.Text);
                                    _EmailHeaders.Add("from", _Value_SubscribeEmailFrom);
                                    _EmailHeaders.Add("subject", _Value_SubscribeEmailSubject);
                                    _EmailHeaders.Add("content-type", "text/html");
                                    SPUtility.SendEmail(_Web, _EmailHeaders, _Value_SubscribeEmailContent + "<br /><br /><a href='" + _Value_ConfirmationUrl + "?email=" + tb_eMail.Text + "&code=" + _ActivationCode + "&action=subscribe'>" + _Value_SubscribeEmailLinkText + "</a>");
                                    lab_Message.Text = _Label_SubscribedText;
                                }
                                else
                                {
                                    lab_Message.Text = _Label_AlreadySubscribedText;
                                }
                            }
                            else if (rb_UnSubscribe.Checked)
                            {
                                if (_EmailExist)
                                {
                                    for (int i = 0; i < _Subscribers.Count; i++)
                                    {
                                        SPListItem _ListItem = _Subscribers[i];
                                        if (tb_eMail.Text == _ListItem["Title"].ToString())
                                        {
                                            StringDictionary _EmailHeaders = new StringDictionary();
                                            _EmailHeaders.Add("to", tb_eMail.Text);
                                            _EmailHeaders.Add("from", _Value_UnSubscribeEmailFrom);
                                            _EmailHeaders.Add("subject", _Value_UnSubscribeEmailSubject);
                                            _EmailHeaders.Add("content-type", "text/html");
                                            SPUtility.SendEmail(_Web, _EmailHeaders, _Value_UnSubscribeEmailContent + "<br /><br /><a href='" + _Value_ConfirmationUrl + "?email=" + tb_eMail.Text + "&code=" + _ListItem["Activation code"].ToString() + "&action=unsubscribe'>" + _Value_UnSubscribeEmailLinkText + "</a>");
                                        }
                                    }
                                    lab_Message.Text = _Label_UnSubscribedText;
                                }
                                else
                                {
                                    lab_Message.Text = _Label_EmailNotValid;
                                }
                            }
                            tb_eMail.Text = "";
                        }
                    }
                }
            });
        }
        #endregion

        #region Methods
        private bool IsValid(List<string> _Values)
        {
            bool _IsValid = true;
            for (int i = 0; i < _Values.Count; i++)
            {
                if (_Values[i] == "") { _IsValid = false; }
            }
            return _IsValid;
        }
        private void ControlsVisibility(bool _Visible) 
        {
            lab_Text.Visible = _Visible;
            tb_eMail.Visible = _Visible;
            rfv_eMail.Visible = _Visible;
            lib_Submit.Visible = _Visible;
            rev_eMail.Visible = _Visible;
            rb_Subscribe.Visible = _Visible;
            rb_UnSubscribe.Visible = _Visible;
        }
        #endregion
    }
}
